package com.darwin.darwinMVC.utils
{
	import com.darwin.darwinMVC.core.IListener;

	/**
	 * command的存储链表
	 * @author lipi
	 */
	public class CmdLinkedList
	{
		public function CmdLinkedList()
		{
		}
		
		
		private var _firstItem:CmdLinkedListItem;
		
		
		/**
		 * 取得一个侦听项
		 */
		public function get firstItem():CmdLinkedListItem
		{
			return _firstItem;
		}
		
		
		/**
		 * 添加一个侦听到链表
		 */
		public function addItem(listener:IListener,priority:int):void
		{
			removeItem(listener);
			
			var $item:CmdLinkedListItem;
			if(_firstItem == null)
			{
				_firstItem = new CmdLinkedListItem(listener,priority);
			}else if(priority < _firstItem.priority){
				$item = new CmdLinkedListItem(listener,priority);
				$item.next = _firstItem;
				_firstItem = $item;
			}else{
				$item = _firstItem;
				while($item != null)
				{
					if($item.next == null)
					{
						$item.next = new CmdLinkedListItem(listener,priority);
						break;
					}else if(priority < $item.next.priority){
						var $newItem:CmdLinkedListItem = new CmdLinkedListItem(listener,priority);
						$newItem.next = $item.next;
						$item.next = $newItem;
						break;
					}else{
						$item = $item.next;
					}
				}
			}
		}
		
		/**
		 * 从链表中删除一个侦听
		 */
		public function removeItem(listener:IListener):void
		{
			if(_firstItem == null) return;
			
			if(_firstItem.listener == listener)
			{
				_firstItem = _firstItem.next;
			}else{
				var $item:CmdLinkedListItem = _firstItem;
				while($item != null)
				{
					if($item.next != null && $item.next.listener == listener)
					{
						$item.next = $item.next.next;
						break;
					}
					$item = $item.next;
				}
			}
		}
		
	}
}